<template>
  <div class="paly-audio">
    <div class="page-audio-dom">
      <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-if="type == 1"
        class="img-box img-box-1">
        <img v-if="!isPlaying" src="@/assets/img/icon-audio.png" alt="" />
        <img v-if="isPlaying" src="@/assets/img/audio-paly-green.gif" alt="" />
      </div>

      <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-if="type == 2"
        class="img-box img-box-2">
        <img v-if="isPlaying" src="@/assets/img/audio=play-or.gif" alt="" />
        <img v-if="!isPlaying" src="@/assets/img/icon-audio-or.png" alt="" />
      </div>
      <div v-if="type == 3">
        <div class="click" @click="handleClickPlayAudio" v-show="isPlaying">
          <slot name="pause"></slot>
        </div>
        <div class="click" @click="handleClickPlayAudio" v-show="!isPlaying">
          <slot name="play"></slot>
        </div>
      </div>
      <div :class="disabled ? 'not-click' : 'click'" @click="handleClickPlayAudio" v-if="type == 4"
        class="img-box img-box-4">
        <img v-if="!isPlaying" src="@/assets/img/icon-audio-s.png" alt="" />
        <img v-show="isPlaying" src="@/assets/img/audio-paly-green-s.gif" alt="" />
      </div>
      <div v-if="type == 5" class="audio-controls record">
        <slot name="controls-custom">
          <span class="right-audio click" @click="
            isPlaying ? handleClickPauseAudio() : handleClickPlayAudio()
            ">
            <i v-if="isPlaying" class="font_family icon-zanting"></i>
            <i v-if="!isPlaying" class="font_family icon-bofang"></i>
          </span>
          <div class="audio-progress">
            <div class="progress-bg">
              <div :style="`width: ${(bufferedTime / totalTime) * 100}%`" class="progress-buffer"></div>
              <div :style="`width: ${(currentTime / totalTime) * 100}%`" class="progress-play"></div>
            </div>
          </div>
          <span class="audio-time">{{ currentAudioTime | filterTime(2, "m") }} /{{
            totalAudioTime | filterTime(2, "m")
          }}
          </span>
        </slot>
      </div>
    </div>
    <audio ref="audioDom" @play="handleAudioPlay" @pause="handleAudioPause" @ended="handleAudioEnded"
      @progress="audioProgress" @timeupdate="timeupdate" @canplay="canplay" :src="audioSrc"></audio>
  </div>
</template>
<script>
// import { throttle1 } from "../utils/utils";
export default {
  data() {
    return {
      speed:1,
      isPlaying: false,
      totalTime: 0,
      currentTime: 0,
      bufferedTime: 0,
      startTime: null,
      endTime: null,
    };
  },
  computed: {
    currentAudioTime() {
      return this.currentTime;
    },
    totalAudioTime() {
      return this.totalTime;
    },
  },
  methods: {
    setTimeToS(str) {
      if (!str) return;
      let millisecond = str.split(".")[1];
      let second = str
        .split(".")[0]
        .split(":")
        .reduce((total, number, index, arr) => {
          return (
            total + parseInt(number) * Math.pow(60, arr.length - index - 1)
          );
        }, 0);
      return second + millisecond / 1000;
    },
    playOneSentence() {
      this.playAudio();
    },
    handleAudioPlay() {
      // 播放音频开始
      console.log("handleAudioPlay");
      // if (this.$route.path.indexOf("/sentence/") != -1 || this.$route.path.indexOf("/text/") != -1) {
      //   this.$refs.audioDom.playbackRate = localStorage.getItem("SPEED")
      // }
      this.$refs.audioDom.playbackRate = this.speed
      this.isPlaying = true;
      console.log(
        "startTime:",
        this.$refs.audioDom && this.$refs.audioDom.currentTime
      );
      this.$emit("audioStart");


    },
    handleAudioEnded() {
      // 播放音频结束
      // console.log("handleAudioPlayEnded");
      this.isPlaying = false;
      console.log(
        "endTime:",
        this.$refs.audioDom && this.$refs.audioDom.currentTime
      );
      this.$emit("audioEnded");
    },
    handleAudioPause() {
      // 播放音频暂停
      // console.log("handleAudioPause");
      this.isPlaying = false;
      console.log(
        "pauseTime:",
        this.$refs.audioDom && this.$refs.audioDom.currentTime
      );
      this.$emit("audioPause");
    },
    handleClickPlayAudio() {
      if (!this.isClick) {
        return;
      }
      if (this.$refs.audioDom && this.isPlaying) {
        if (this.isAllowPause) {
          this.$refs.audioDom.pause();
        } else {
          this.$refs.audioDom.currentTime = 0;
        }
      } else {
        this.playAudio(this.audioStartTime, this.audioEndTime);
      }
    },
    handleClickPauseAudio() {
      if (!this.isClick) {
        return;
      }
      this.pauseAudio();
    },
    playAudio() {
      let startTime = this.analysisTime(
        this.sentenceList[this.playNum].startTime
      );
      this.$refs.audioDom.currentTime = startTime - 0.5;
      // console.log(this.$refs.audioDom);
      this.$refs.audioDom.play();
    },
    pauseAudio() {
      if (this.$refs.audioDom) {
        this.$refs.audioDom.pause();
      }
    },
    initAudioPlay() {
      this.isPlaying = false;
      this.$refs.audioDom.load();
      this.$refs.audioDom.playbackRate = this.speed
    },
    audioProgress() {
      console.log(this.$refs.audioDom.buffered);
      // this.bufferedTime = this.$refs.audioDom.buffered.end(
      //   this.$refs.audioDom.buffered.length - 1
      // );
    },
    timeupdate: function (e) {
      if (this.sentenceList.length == 0) {
        return;
      }
      let currentTime = e.target.currentTime;
      let curStartTime = this.analysisTime(
        this.sentenceList[this.playNum].startTime
      );
      let curEndTime = this.analysisTime(
        this.sentenceList[this.playNum].endTime
      );

      if (
        this.sentenceList.length - 1 == this.playNum &&
        curEndTime &&
        currentTime >= curEndTime
      ) {
        this.$refs.audioDom.pause();
      } else if (this.sentenceList.length - 1 == this.playNum && !curEndTime) {
        return;
      }
      if (this.playNum + 1 >= this.sentenceList.length) {
        return;
      }
      let nextStartTime = this.analysisTime(
        this.sentenceList[this.playNum + 1].startTime
      );

      if (!this.isPlayAll && currentTime > curEndTime - 0.5) {
        this.$refs.audioDom.pause();
        return;
      }
      if (curEndTime - 0.1 >= currentTime && currentTime >= curStartTime) {
        return;
      } else if (currentTime > curEndTime - 0.1) {
        if (nextStartTime != curEndTime) {
          this.$refs.audioDom.currentTime = nextStartTime - 0.3;
        }
        this.$emit("setPlayNum", this.playNum + 1);
      }
    },
    analysisTime(data) {
      if (!data) {
        return "";
      }
      let result = data.split(":");
      let returnBack = 0;
      let s = 0;
      let m = 0;
      let h = 0;
      s = parseFloat(result[result.length - 1]);
      m = parseFloat(result[result.length - 2]);
      if (result.length > 2) {
        h = parseFloat(result[0]);
      }
      returnBack = h * 60 * 60 + m * 60 + s;
      return returnBack;
    },
    canplay() {
      this.totalTime = this.$refs.audioDom.duration;
    },
  },
  mounted() {
    if(this.$route.path.indexOf("/sentence/") != -1 || this.$route.path.indexOf("/text/") != -1){
      this.speed=Number(localStorage.getItem("SPEED"))||1
    }
    // this.initAudio();
    this.initAudioPlay();
  },
  beforeDestroy() { },
  props: {
    isPlayAll: {
      type: Boolean,
      default: false,
    },
    sentenceList: {
      type: Array,
    },
    playNum: {
      type: Number,
    },
    // 页面展示图标
    type: {
      type: Number,
      default: 2,
    },
    // 是否允许暂停
    isAllowPause: {
      type: Boolean,
      default: false,
    },
    // 是否禁止点击
    disabled: {
      type: Boolean,
      default: false,
    },
    isClick: {
      type: Boolean,
      default: true,
    },
    // 音频属性
    // 地址
    audioSrc: {
      type: String,
      default: "",
      // "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&spd=2&text='My name is Ben. This is my family photo. This boy is me. My father is a doctor. He likes reading newspapers very much. My mother is an engineer. She likes reading books. This is my little sister. She is five years old. She likes collecting toys. She has two teddy bears and three toy cats. I like playing football. I often play it with my friends on Saturdays and Sundays.'",
    },
    audioStartTime: {
      default: null,
    },
    audioEndTime: {
      default: null,
    },
    // 是否静音 muted

    // 音量 volume  规定音频/视频的当前音量。必须是介于 0.0 与 1.0 之间的数字。
    // 播放速度 playbackRate
    /**
     *  1.0 正常速度
        0.5 半速（更慢）
        2.0 倍速（更快）
        -1.0 向后，正常速度
        -0.5 向后，半速
     */
  },
  watch: {
    audioSrc() {
        this.initAudioPlay();
    },
    isPlaying() {
        this.$emit("onIsPlay", this.isPlaying);  
    },
  },
};
</script>
